package edu.sias.hyznxfapi.controller;


import edu.sias.hyznxfapi.chat.imageCom.BigModelNew;
import edu.sias.hyznxfapi.vo.ImageVo;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;

/**
 * 图片理解
 */
@RestController
@RequestMapping("/xfapi/ImageUnderstand")
public class ImageUnderstandController {
    //传递的参数是：一段话 + 图片地址
    @PostMapping()
    public String upload(@RequestBody ImageVo imageVo) throws Exception {
        System.out.println("imageVo: " + imageVo);
        String text = imageVo.getText();
        System.out.println("text: " + text);
        String base64String = imageVo.getImageUrl();

        // 去除Base64字符串中的数据URL部分
        if (base64String.startsWith("data:image")) {
            base64String = base64String.split(",")[1];
        }

        // 解码Base64字符串
        byte[] decodedBytes = Base64.getDecoder().decode(base64String);

        // 创建存储路径，例如 D:/image
        String directoryPath = "C:/image";
        // 检查目录是否存在，如果不存在则创建
        File directory = new File(directoryPath);
        if (!directory.exists()) {
            directory.mkdirs(); // 创建目录
        }

        // 创建文件名，使用日期时间戳
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss");
        LocalDateTime now = LocalDateTime.now();
        String fileName = "image_" + dtf.format(now) + ".png";

        // 构建图片文件的完整路径
        File imageFile = new File(directory, fileName);

        // 从Base64解码的字节数组创建BufferedImage对象
        BufferedImage image = ImageIO.read(new java.io.ByteArrayInputStream(decodedBytes));

        // 将BufferedImage对象写入文件
        ImageIO.write(image, "png", imageFile);

        System.out.println("图片保存成功，路径：" + imageFile.getAbsolutePath());

        //实例
        String apiResult = new BigModelNew("", false).getApiResult(text, imageFile.getAbsolutePath());
//        String apiResult = new BigModelNew("", false).getApiResult(text, "D://11//xf_image.jpg");
        System.out.println("结果：：：" + apiResult);
        // 检查文件是否存在并且可以删除
        if (imageFile.exists() && !imageFile.isDirectory()) {
            boolean isDeleted = imageFile.delete();
            if (isDeleted) {
                System.out.println("文件删除成功: " +  imageFile.getAbsolutePath());
            } else {
                System.out.println("文件删除失败: " +  imageFile.getAbsolutePath());
            }
        } else {
            System.out.println("文件不存在或是一个目录: " +  imageFile.getAbsolutePath());
        }
        return apiResult;
    }
}
